from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import MultiPartParser
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
import os

class UploadFile(APIView):
  renderer_classes = [JSONRenderer]
  parser_classes = [MultiPartParser]

  def post(self, request):
    file_obj = request.data['file']
    file_name = request.data['name']

    # 保存文件到MEDIA_ROOT指定的目录下
    relative_path = default_storage.save(
      os.path.join('uploads', file_name),
      ContentFile(file_obj.read())
    )

    # 绝对路径
    absolute_path = os.path.join(settings.MEDIA_ROOT, relative_path)

    print('相对路径 ', relative_path)
    print('绝对路径 ', absolute_path)
    
    return Response('上传文件', content_type="application/json")
